package com.itrip.itripauth.controller;


import com.alibaba.fastjson.JSONArray;
import com.itrip.common.vo.UserVo;
import com.itrip.itripauth.config.SystemConfig;
import com.itrip.itripauth.entity.HotelOrder;
import com.itrip.itripauth.entity.HotelRoom;
import com.itrip.itripauth.service.HotelOrderService;
import com.itrip.itripauth.service.HotelRoomService;
import com.itrip.itripauth.service.HotelTempStoreService;
import com.itrip.itripauth.service.OrderLinkUserService;
import com.itrip.itripauth.util.*;
import com.itrip.itripauth.vo.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 四阶段项目二组
 * @since 2020-02-25
 */
@RestController
@RequestMapping("/biz/api/hotelorder")
@CrossOrigin
public class HotelOrderController {

    @Autowired
    private HotelOrderService hotelOrderService;

    @Resource
    private HotelRoomService roomService;

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private OrderLinkUserService orderLinkUserService;

    @Autowired
    private HotelTempStoreService hotelTempStoreService;

    /**
     *根据个人订单列表
     * @param hotelOrderVo
     * @param request
     * @return
     */
    @RequestMapping(value = "/getpersonalorderlist", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Object> getPersonalOrderList(@RequestBody HotelOrderVo hotelOrderVo,
                                            HttpServletRequest request) {
        //验证token是否过期
        String token = request.getHeader("token");
        System.out.println(token);
//验证token
        UserVo userVo=null;
        try {
            Claims claims = JwtUtil.checkToken(token);
            System.out.println(claims);
            claims.remove(claims.getSubject());
            userVo= (UserVo) redisUtil.get(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        if (userVo==null){
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        System.out.println(hotelOrderVo.toString());
        hotelOrderVo.setUserId(userVo.getId());
        //hotelOrderVo.setUserId(29L);
        PageVo<HotelOrder> getpersonalorderinfo= hotelOrderService.getPersonalOrderList(hotelOrderVo);
        return DtoUtil.returnDataSuccess(getpersonalorderinfo);

    }



    @RequestMapping(value = "/getpersonalorderinfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Object> getPersonalOrderInfo(@ApiParam(required = true, name = "orderId", value = "订单ID")
                                            @PathVariable String orderId,
                                            HttpServletRequest request) {
        //验证token是否过期
        String token = request.getHeader("token");
        System.out.println(token);
//验证token
        UserVo userVo=null;
        try {
            Claims claims = JwtUtil.checkToken(token);
            System.out.println(claims);
            claims.remove(claims.getSubject());
            userVo= (UserVo) redisUtil.get(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        if (userVo==null){
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        HotelOrder hotelOrder= hotelOrderService.getHotelOrderById(orderId);
        PersonalHotelOrderVO personalHotelOrderVO=new PersonalHotelOrderVO();
        personalHotelOrderVO.setId(hotelOrder.getId());
        personalHotelOrderVO.setBookType(hotelOrder.getBookType());
        personalHotelOrderVO.setCreationDate(hotelOrder.getCreationDate());
        personalHotelOrderVO.setOrderNo(hotelOrder.getOrderNo());
        //查询预订房间的信息
        HotelRoom room = roomService.getHotelRoomById(hotelOrder.getRoomId());
        if (room!=null) {
            personalHotelOrderVO.setRoomPayType(room.getPayType());
        }
        Integer orderStatus = hotelOrder.getOrderStatus();
        personalHotelOrderVO.setOrderStatus(orderStatus);
        if (orderStatus == 1) {
            personalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessCancel()));
            personalHotelOrderVO.setProcessNode("3");
        } else if (orderStatus == 0) {
            personalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            personalHotelOrderVO.setProcessNode("2");//订单支付
        } else if (orderStatus == 2) {
            personalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            personalHotelOrderVO.setProcessNode("3");//支付成功（未出行）
        } else if (orderStatus == 3) {
            personalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            personalHotelOrderVO.setProcessNode("5");//订单点评
        } else if (orderStatus == 4) {
            personalHotelOrderVO.setOrderProcess(JSONArray.parse(systemConfig.getOrderProcessOK()));
            personalHotelOrderVO.setProcessNode("6");//订单完成
        } else {
            personalHotelOrderVO.setOrderProcess(null);
            personalHotelOrderVO.setProcessNode(null);
        }
        personalHotelOrderVO.setPayAmount(hotelOrder.getPayAmount());
        personalHotelOrderVO.setPayType(hotelOrder.getPayType());
        personalHotelOrderVO.setNoticePhone(hotelOrder.getNoticePhone());
        return DtoUtil.returnSuccess("获取个人订单信息成功", personalHotelOrderVO);

    }

    /**
     * 获取个人订单房型信息
     * @param orderId
     * @param request
     * @return
     */
    @RequestMapping(value = "/getpersonalorderroominfo/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Object> getPersonalOrderRoomInfo(@ApiParam(required = true, name = "orderId", value = "订单ID")
                                                @PathVariable String orderId,
                                                HttpServletRequest request) {
        //验证token是否过期
        String token = request.getHeader("token");
        System.out.println(token);
//验证token
        Dto<Object> dto = null;
        UserVo userVo=null;
        try {
            Claims claims = JwtUtil.checkToken(token);
            System.out.println(claims);
            claims.remove(claims.getSubject());
            userVo= (UserVo) redisUtil.get(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        if (userVo==null){
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        try {
            PersonalOrderRoomVO vo = hotelOrderService.getHotelOrderRoomInfoById(Long.valueOf(orderId));
            if (null != vo) {
                dto = DtoUtil.returnSuccess("获取个人订单房型信息成功", vo);
            } else {
                dto = DtoUtil.returnFail("没有相关订单房型信息", "100530");
            }
        } catch (Exception e) {
            e.printStackTrace();
            dto = DtoUtil.returnFail("获取个人订单房型信息错误", "100531");
        }
        return dto;
    }


    /**
     * 根据订单ID获取订单信息
     * @param orderId
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryOrderById/{orderId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Object> queryOrderById(@ApiParam(required = true, name = "orderId", value = "订单ID") @PathVariable Long orderId,HttpServletRequest request) {
        ModifyHotelOrderVO modifyHotelOrderVO = null;
        //验证token是否过期
        String token = request.getHeader("token");
        System.out.println(token);
//验证token
        Dto<Object> dto = null;
        UserVo userVo=null;
        try {
            Claims claims = JwtUtil.checkToken(token);
            System.out.println(claims);
            claims.remove(claims.getSubject());
            userVo= (UserVo) redisUtil.get(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        if (userVo==null){
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        HotelOrder order = hotelOrderService.getHotelOrderById(orderId);
        if (order==null) {
            return DtoUtil.returnFail("100533", "没有查询到相应订单");
        }
        modifyHotelOrderVO = new ModifyHotelOrderVO();
        BeanUtils.copyProperties(order, modifyHotelOrderVO);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("orderId", order.getId());
        List<OrderLinkUserVo> itripOrderLinkUserList = orderLinkUserService.getOrderLinkUserListByMap(param);
        modifyHotelOrderVO.setItripOrderLinkUserList(itripOrderLinkUserList);
        return DtoUtil.returnSuccess("获取订单成功", modifyHotelOrderVO);

    }


    @GetMapping("/gethotelorderroomid/{hotelId}/{orderId}")
    public Dto getHotelOrderRoomId(@PathVariable Integer hotelId, @PathVariable Integer orderId, HttpServletRequest request) {

        return DtoUtil.returnDataSuccess(hotelOrderService.getHotelOrderRoomId(hotelId, orderId));
    }

    @PostMapping("/getpreorderinfo")
    public Dto getPreorderInfo(@RequestBody AddOrderVo addOrderVo){

        try {
            RoomStoreVO roomStoreVO = hotelTempStoreService.getPreorderInfo(addOrderVo);
            if (roomStoreVO.getCount()>=addOrderVo.getCount()) {
                return DtoUtil.returnSuccess("还有房间", roomStoreVO);
            }else {
                return DtoUtil.returnFail("房间以满");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("查询订单信息失败");
        }
    }
    @PostMapping("/addhotelorder")
    public Dto addHotelOrder(@RequestBody AddOrderVo addOrderVo,HttpServletRequest request){
        //验证token是否过期
        String token = request.getHeader("token");
        System.out.println(token);
        //验证token
        Dto<Object> dto = null;
        UserVo userVo=null;
        try {
            Claims claims = JwtUtil.checkToken(token);
            System.out.println(claims);
            claims.remove(claims.getSubject());
            userVo= (UserVo) redisUtil.get(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        if (userVo==null){
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }
        addOrderVo.setUserId(userVo.getId());
        try{
            Map<String, String> map;
            if (null==addOrderVo.getId()) {
                map = hotelOrderService.addHotelOrder(addOrderVo);
            }else{
                map = hotelOrderService.updateOrder(addOrderVo);
            }
            if (map != null) {
                return DtoUtil.returnSuccess("预定成功", map);
            }
            return DtoUtil.returnFail("预定失败");
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("未知错误,预定失败");
        }
    }
}
